//
//  ViewController4.m
//  201-数据存储
//
//  Created by student on 16/3/14.
//  Copyright © 2016年 NIIT. All rights reserved.
//

#import "ViewController4.h"
#import "studentModel.h"

#define kCodeKey @"student"


@interface ViewController4 ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *ageTextField;
@property (weak, nonatomic) IBOutlet UITextField *IDTextField;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic,strong) NSMutableArray *stuArr;

@end

@implementation ViewController4

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

-(NSArray *)stuArr{
    if (_stuArr == nil) {
        NSFileManager *fm = [NSFileManager defaultManager];
        if ([fm fileExistsAtPath:[self archPath]]) {
            //进行解档
            //1读出数据
            NSData *data = [NSData dataWithContentsOfFile:[self archPath]];
            //2.创建解档对象
            NSKeyedUnarchiver *unArch = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
            //3.从解档对象中解档Student（和归档时使用同一个Key）
            _stuArr = [unArch decodeObjectForKey:kCodeKey];
            //4.完成解档
            [unArch finishDecoding];
        }
        if (_stuArr == nil) {
             _stuArr = [NSMutableArray array];
        }
        
        
    }
    return _stuArr;
}

-(NSString *)archPath{
    NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *archPath = [docPath stringByAppendingPathComponent:@"stus.arch"];
    return archPath;
}

- (void)save {
    //1.创建可变数据对象用于归档存入
    NSMutableData *mData = [NSMutableData data];
    //2.创建归档对象
    NSKeyedArchiver *arch = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mData];
    
    //3.归档数组对象（数组本身是支持归档，数组中的元素也要支持归档）
    [arch encodeObject:self.stuArr forKey:kCodeKey];
    //4.完成归档
    [arch finishEncoding];
    //5.数据存入文件
    [mData writeToFile:[self archPath] atomically:YES];
    
    [self.tableView reloadData];
}
- (IBAction)add:(id)sender {
    studentModel *m = [[studentModel alloc] init];
    m.stuID = self.IDTextField.text;
    m.stuAge = self.ageTextField.text;
    m.stuName = self.nameTextField.text;
    [self.stuArr addObject:m];
    [self save];
    
}
- (IBAction)delete:(id)sender {
    for (studentModel *m in self.stuArr) {
        if ([m.stuID isEqualToString:self.IDTextField.text]) {
            [self.stuArr removeObject:m];
            break;
        }
    }
    [self save];
    
}
- (IBAction)modify:(id)sender {
    for (studentModel *m in self.stuArr) {
        if ([m.stuID isEqualToString:self.IDTextField.text]) {
            m.stuAge = self.ageTextField.text;
            m.stuName = self.nameTextField.text;
            break;
        }
    }
    [self save];
    
    [self.tableView reloadData];
}
- (IBAction)find:(id)sender {
    for (studentModel *m in self.stuArr) {
        if ([m.stuID isEqualToString:self.IDTextField.text]) {
            self.nameTextField.text = m.stuName;
            self.ageTextField.text = m.stuAge;
            break;
        }
    }
}
- (IBAction)findAll:(id)sender {
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - TableViewDataSource Delegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.stuArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
//    if (cell == nil) {
//        cell = [UITableViewCell alloc] initWithStyle:<#(UITableViewCellStyle)#> reuseIdentifier:<#(nullable NSString *)#>
//    }
    UILabel *labe1 = [cell.contentView viewWithTag:101];
    UILabel *labe2 = [cell.contentView viewWithTag:102];
    UILabel *labe3 = [cell.contentView viewWithTag:103];
    studentModel *m = self.stuArr[indexPath.row];
    labe1.text = m.stuID;
    labe2.text = m.stuAge;
    labe3.text = m.stuName;
    
    return cell;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
@end














